package com.hulman.oms.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Sparepart;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.SparepartWarehouse;
import com.hulman.oms.service.SparepartService;
import com.hulman.oms.service.SparepartWarehouseService;
import com.hulman.oms.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: maxwellens
 */
@RestController
public class SparepartController
{
    @Autowired
    private SparepartService sparepartService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private SparepartWarehouseService sparepartWarehouseService;

    @GetMapping("/spareparts/{id}")
    public Result findSparepartById(@PathVariable Integer id)
    {
        Sparepart Sparepart = sparepartService.findSparepartById(id);
        return new Result(Sparepart);
    }

    @GetMapping("/spareparts")
    public Result findspareparts(Integer page, Integer limit, Integer type, String name, String brand, String model,Integer warehouseId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("type", type);
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        map.put("warehouseId", warehouseId);
        return sparepartService.findSparepartsResult(map);
    }

    @GetMapping("/spareparts/group")
    public Result findsparepartsByGroup()
    {
        List<Sparepart> spareparts = sparepartService.findSpareparts(new HashMap<>());
        Map<String, List<Sparepart>> groupedSpareparts = spareparts.stream().collect(Collectors.groupingBy(Sparepart::getTypeText));
        return new Result(groupedSpareparts);
    }

    @DeleteMapping("/spareparts/{ids}")
    public Result deleteSparepartById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            sparepartService.deleteSparepartById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/spareparts")
    public Result saveSparepart(Sparepart Sparepart)
    {
        sparepartService.saveSparepart(Sparepart);
        return Result.SUCCESS;
    }

    /**
     * 通过Excel批量导入备件信息
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/spareparts/import")
    public Result importspareparts(MultipartFile file) throws IOException
    {
        File tmp = new File(System.getProperty("java.io.tmpdir") + "/" + System.currentTimeMillis() + ".xlsx");
        file.transferTo(tmp);
        List<Sparepart> spareparts = EasyExcel.read(tmp).head(Sparepart.class).sheet(0).doReadSync();
        for (Sparepart sparepart : spareparts)
        {
            sparepart.setType(Sparepart.parseType(sparepart.getExcelTypeText()));
            if (sparepart.getQuantity() == null)
            {
                sparepart.setQuantity(0);
            }

            if(sparepart.getWarehouseName()!=null && sparepart.getWarehouseName()!=""){
                SparepartWarehouse sparepartWarehouse = sparepartWarehouseService.selectByName(sparepart.getWarehouseName());
                sparepart.setWarehouseId(sparepartWarehouse.getId());
            }
            sparepartService.saveSparepart(sparepart);
        }
        return Result.SUCCESS;
    }

    /**
     * 导出备件列表
     *
     * @throws IOException
     */
    @GetMapping("/spareparts/export")
    public void exportSpareparts(String name, String brand, String model,String warehouseId) throws IOException
    {
        String fileName = "备件清单.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        map.put("warehouseId", warehouseId);
        List<Sparepart> spareparts = sparepartService.findSpareparts(map);
        for (Sparepart sparepart : spareparts)
        {
            sparepart.setExcelTypeText(sparepart.getTypeText());
        }
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "备品备件").head(Sparepart.class).build();
        excelWriter.write(spareparts, sheet0);
        excelWriter.finish();
    }

    @GetMapping("/spareparts/warn")
    public Result findWarnSpareparts(Integer page, Integer limit, Integer type, String name, String brand, String model,Integer warehouseId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("type", type);
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        map.put("warehouseId", warehouseId);
        return sparepartService.findWarnSparepartsResult(map);
    }
}
